import os
import re
import requests

TRANS_STR="!#!#TRANS#!#!"
NEWLINE_STR="\\n"
ENCODE="utf_8"
API_HOST = "192.168.10.22"
API_PORT = "4999"
API_URI = "/trans"

data = []

# 输入的HTML字符串
html_str_array = [
    '<el-table-column prop="name" label="a 啊" >',
    '>删 除<',
    " callback(new Error('不能为空'))",
    "this.$confirm('您是否要删除所有选中的数据？', '提示', {",
    "confirmButtonText: '确定',",
    "cancelButtonText: '取消',",
    "message: '删除成功',",
    "this.$messages.error('请至少选择一条数据进行删除')",
    "this.$messages.success('执行成功！')",
    '< placeholder="密码" v-model="ruleForm.password">'
]


#翻译接口
def _api(msgids, from_lang="zh_CN", dst_lang="en_US", api_type="baidu"):
    url = "http://{}:{}{}".format(API_HOST, API_PORT, API_URI)
    payload = {'from_lang':from_lang, 'dst_lang':dst_lang, "api_type":api_type, "msgids":msgids}
    r = requests.post(url, json=payload).json()
    if "res" not in r:
        raise Exception("翻译服务器错误，{}".format(r['err']))
    return r["res"]

# 匹配需要翻译内容
def translate_pattern(html_text):
    translate_pattern = [
        r"\$t\('[^']*[\u4e00-\u9fff]+[^']*'\)",
        r'\$t\("[^"]*[\u4e00-\u9fff]+[^"]*"\)'
        # r"\$t\('([^\"]*[\u4e00-\u9fff]+[^\"]*?)'\)", # 匹配$t('xx')内包含中文
        # r' title="([^$t"]*[\u4e00-\u9fff]+[^$t"]*)"',  # 匹配 title标签内包含中文,前包含空格
        # r' label="([^$t"]*[\u4e00-\u9fff]+[^$t"]*)"',  # 匹配 label标签内包含中文,前包含空格
        # r'>([^$t"]*[\u4e00-\u9fff]+[^$t"]*)<',  # 匹配><标签内包含中文
        # r'new Error\(\'([^$t"]*[\u4e00-\u9fff]+[^$t"]*)\'\)',  # 匹配callback(new Error('')内包含中文
        # r'this\.\$confirm\(\'([^$t"]*[\u4e00-\u9fff]+[^$t"]*)\', \'([^$t"]*[\u4e00-\u9fff]+[^$t"]*)\', {',  # 匹配this.$confirm()内包含中文
        # r'confirmButtonText: \'([^$t"]*[\u4e00-\u9fff]+[^$t"]*)\',',  # 匹配confirmButtonText: ''内包含中文
        # r'cancelButtonText: \'([^$t"]*[\u4e00-\u9fff]+[^$t"]*)\',',  # 匹配cancelButtonText: ''内包含中文
        # r'message: \'([^$t"]*[\u4e00-\u9fff]+[^$t"]*)\',',  # 匹配message: ''内包含中文
        # r'this\.\$messages\.error\(\'([^$t"]*[\u4e00-\u9fff]+[^$t"]*)\'\)',  # 匹配this.$messages.error()内包含中文
        # r'this\.\$messages\.success\(\'([^$t"]*[\u4e00-\u9fff]+[^$t"]*)\'\)',  # 匹配this.$messages.error()内包含中文
        # r' placeholder="([^$t"]*[\u4e00-\u9fff]+[^$t"]*)"',  # 匹配 placeholder标签内包含中文,前包含空格
        # r'return\s+["\']([^$t"]*[\u4e00-\u9fff]+[^$t"]*)["\']',  # 匹配 return 标签内包含中文,
        # # r' :title=["\']([^"]+)["\']',  # 匹配 :title标签内所有内容,前包含空格
    ]
    for pattern in translate_pattern:
        matches = re.findall(pattern, html_text)

        # 输出匹配到的中文
        if matches:
            for chinese_text in matches:
                data.append(chinese_text[4:-2])




def read_write_file(path):
    with open(path, 'r+', encoding='utf-8') as f:  # 打开文件
        lines = f.readlines()  # 读取所有行
        for i in range(len(lines)):
            # 翻译
            translate_pattern(lines[i])

def traverse_dir(path):
    for file_name in os.listdir(path):
        abs_path = os.path.join(path, file_name)
        if os.path.isdir(abs_path):
            traverse_dir(abs_path) # 如果是文件夹，则递归调用自己
        else:
            if file_name.endswith(".vue") or file_name.endswith(".js"):
                read_write_file(abs_path)


if __name__ == "__main__":

    # # 指定翻译json保存的文件路径
    # en_json_file_name = "C:/Users/bch101213/Desktop/en_data.js"
    # cn_json_file_name = "C:/Users/bch101213/Desktop/cn_data.js"
    # # 指定要遍历的根文件夹
    # root_folder = 'C:/Users/bch101213/Desktop/vue'  # 替换成你的根文件夹路径


    # 指定翻译json保存的文件路径
    en_json_file_name = "lang/en_data.js"
    cn_json_file_name = "lang/cn_data.js"
    # 指定要遍历的根文件夹
    root_folder = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
    # 遍历文件，匹配需要翻译文本
    traverse_dir(root_folder)

    data = list(set(data))
    translate_data = _api(data)


    # 生成 JavaScript 代码
    en_js_code = "export default {\n"
    cn_js_code = "export default {\n"
    for i in range(len(data)):
        en_js_code += f"  '{data[i]}': \"{translate_data[i]}\",\n"
        cn_js_code += f"  '{data[i]}': '{data[i]}',\n"

    en_js_code += "}"
    cn_js_code += "}"

    # 将 JavaScript 代码写入文件
    with open(os.path.join(root_folder,en_json_file_name), 'w+', encoding="utf-8") as file:
        file.write(en_js_code)


    # 将 JavaScript 代码写入文件
    with open(os.path.join(root_folder,cn_json_file_name), 'w+', encoding="utf-8") as file:
        file.write(cn_js_code)
